<template>
  <div class="variable">
    <SSection name="实例变量">
      <template v-slot:header>
        <div class="tool">
          <i class="tool-add iconfont icon-add" @click="addVar"></i>
        </div>
      </template>
      <div>
        <SProp v-for="(item, index) in data" :key="index"
               @menu.prevent="onMenu($event,item)"
               :data="item.value"
               :ext="item"
               @update:data="onUpDateVar"
               :label="item.name">
        </SProp>
      </div>
    </SSection>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue';
import { showVar } from '../scene/inquirer';
import SSection from '@/ui-kit/section/section.vue';
import assetsStore from '../store/assets';
import SProp from '@/ui-kit/prop/prop.vue';
import { showMenuByMouseEvent } from '@/ui-kit/menu';
import propertyStore from './store';
import { sceneAssistant } from '../scene';

export default defineComponent({
  name: 'variable',
  components: { SProp, SSection },
  emits: [],
  props: {},
  setup(props, { emit }) {
    const data = computed(() => {
      return propertyStore().variables;
    });

    return {
      data,
      addVar() {
        showVar({ title: '添加实例变量' }, (data: sail.Variable) => {
          const id = propertyStore().originObjectID;
          assetsStore().addVariable(data, id);
        });
      },
      onUpDateVar(val: string | boolean | number, item: sail.Variable) {
        // 这里修改的是实例，不是源对象
        sceneAssistant.modifyVariable(item.id, val);
      },
      onMenu(event: MouseEvent, data: sail.Variable) {
        const id = propertyStore().originObjectID;
        showMenuByMouseEvent(event, [
          {
            name: '删除',
            callback: () => {
              assetsStore().removeVariable(data, id);
            },
          },
          {
            name: '编辑',
            callback: () => {
              showVar(
                {
                  title: '编辑实例变量',
                  data: data.id,
                },
                (item: sail.Variable) => {
                  const id = propertyStore().originObjectID;
                  assetsStore().modifyVariableValue(id, data.id, item);
                });
            },
          },
        ]);
      },
    };
  },
});
</script>
<style scoped lang="scss">
.variable {
  .tool {
    flex: 1;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;

    .tool-add {
      cursor: pointer;
    }
  }
}
</style>
